package cn.bopomo.dealer.base.action.ajax;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.bopomo.dealer.base.action.BaseAction;
import cn.bopomo.dealer.base.common.CommonConstant;
import cn.bopomo.dealer.base.common.ServiceConfig;
import cn.bopomo.dealer.base.service.IOperatorService;
import cn.bopomo.dealer.base.util.Page;
import cn.bopomo.dealer.base.vo.ModuleList;
import cn.bopomo.dealer.base.vo.OperatorDetail;

public class LoadOperatorListAjax extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control","no-cache");
		
		//获取当前操作员ID
		String userId = this.getUserId(request);
		if(userId == null){
			return this.findFailure(mapping);
		}
		//获取当前分页数
		String strPageSize = request.getParameter("pageSize");
		if (strPageSize == null || "".equals(strPageSize)){
			strPageSize = "1";
		}
		//设置每页记录数

		IOperatorService service = (IOperatorService)this.findService(ServiceConfig.OPERATOR_SERVICE);
		//获取当前操作员对象
		OperatorDetail operatorDetail = service.getOperatorDetail(userId);
		//获取查询列表
		Page resultPage = service.getOperatorListByParent(operatorDetail, Integer.parseInt(strPageSize),CommonConstant.INT_ROWS_PER_PAGE);
		//设置分页查询的提交URL
		if (resultPage != null && resultPage.getList().size()>0){
			resultPage.setTarget(request.getRequestURI());
		}
		List operatorList = resultPage.getList();
		resultPage.setAJAX(true);
		
		if (operatorList != null && operatorList.size()>0){
			JSONArray  array = this.toJsonArray(operatorList);
			JSONObject json = new JSONObject();
			json.put("operators", array);
			json.put("pageStr", resultPage.getPageStr());
			response.getWriter().write(json.toString());
			return null;
		}else{
			response.getWriter().write("");
			return null;
		}
		
		
		
		
		
	}

	/**
	 * 将List转化为JSON数组
	 * @param objectList
	 * @return
	 */
	protected JSONArray toJsonArray(List objectList) {
		JSONArray  array = new JSONArray();
		for (int i = 0;i<objectList.size();i++){
			OperatorDetail tmp = (OperatorDetail)objectList.get(i);
			JSONObject json = new JSONObject();
			json.put("id",tmp.getId().toString());
			json.put("loginName", tmp.getLoginName());
			json.put("addDate", tmp.getAddDate().toLocaleString());
			array.put(json);
		}
		return array;
	}
}
